package org.tio.sitexxx.web.server.controller.minip;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.service.model.main.Coupon;
import org.tio.sitexxx.service.model.main.Member;
import org.tio.sitexxx.service.model.main.Payment;
import org.tio.sitexxx.service.model.main.Wardrobe;
import org.tio.sitexxx.service.service.qj.CouponService;
import org.tio.sitexxx.service.service.qj.MemberService;
import org.tio.sitexxx.service.service.qj.PaymentService;
import org.tio.sitexxx.service.service.qj.WardrobeService;
import org.tio.sitexxx.web.server.utils.ObjectToMap;
import org.tio.utils.resp.Resp;

import java.sql.SQLException;
import java.util.*;


@RequestPath(value = "/wardrobe")
public class WardrobeController {
    private static Logger log = LoggerFactory.getLogger(WardrobeController.class);

    /**
     * 返回个人衣橱，个人衣橱的作用是供顾问在回答用户的一元提问时提供参考作用
     *
     * @param openid
     * @return
     */
    @RequestPath(value = "/list")
    public List<Wardrobe> list(String openid) {
        if (null == openid) return null;
        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);
        query.put("memberId", Member.getId());
        List<Wardrobe> result = WardrobeService.me.getWardrobes(query);
        return result;
    }

    /**
     * 和上面的接口有点冗余，想不明白以前的学长为啥写成这样，这让我十分难受
     *
     * @param id
     * @return
     */
    @RequestPath(value = "/member/list")
    public Resp memberList(Integer id) {
        if (null == id) return Resp.fail("参数错误");
        Map<String, Object> query = new HashMap<>();
        query.put("memberId", id);
        List<Wardrobe> result = WardrobeService.me.getWardrobes(query);
        return Resp.ok(result);
    }

    /**
     * 数据库记录初始化
     *
     * @param request
     * @return
     */
    @RequestPath(value = "/upsert")
    public Map<String, Object> upsert(HttpRequest request) {
        //String wardrobe
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        String openid = (String) body.get("openid");
        JSONArray wardrobes = JSON.parseArray(JSON.toJSONString(body.get("wardrobe")));//接收衣橱数组类似[{},{}....]
//        ArrayList<String> wardrobes = (ArrayList<String>) body.get("wardrobe");
        Map<String, Object> query = new HashMap<>();
        Map<String, Object> result = new HashMap<>();

        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);

        Record wardrobe;
        List<Integer> ids = new ArrayList<>();

        for (int i = 0; i < wardrobes.size(); i++) {
            System.out.println("添加的衣橱数量：" + wardrobes.get(i));
            Map<String, Object> map = JSON.parseObject(wardrobes.getString(i));
            wardrobe = new Record().set("tag", map.get("tag")).set("picture", map.get("picture")).set("texture", map.get("texture"))
                    .set("length", map.get("length")).set("paid", 0).set("memberId", Member.getId())
                    .set("createdAt", new Date()).set("updatedAt", new Date());
            Db.save("wardrobe", "id", wardrobe);
            ids.add(wardrobe.get("id"));
        }
        result.put("id", ids);
        return result;
    }

    /***
     * 订单初始化
     * @param request
     * @return
     */
    @RequestPath(value = "/pay/init")
    public Map<String, Object> pay_init(HttpRequest request) {
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        //优惠卷id
        Integer coupon_id = (Integer) body.get("coupon_id");
        System.out.println("coupon_id:" + coupon_id);
        //问题id
        Integer wardrobe_id = (Integer) body.get("wardrobe_id");
        //需付金额
        Integer amount_payable = (Integer) body.get("amount_payable");

        String openid = (String) body.get("openid");

        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);

        Member Member = MemberService.me.getMember(query);


        Integer value;
        Coupon Coupon;
        if (coupon_id != null) {
            query.put("id", coupon_id);
            Coupon = CouponService.me.getCouponById(coupon_id);
            value = Coupon == null ? 0 : Coupon.getValue();
        } else {
            Coupon = null;
            value = 0;
        }


        System.out.println(Member);
        int discount_amount = 0;
        //应付金额
        Integer payable = amount_payable;
        int delta = payable - value;

        //实付金额
        int pay_amount = (delta > 0) ? delta : 0;
        //折扣金额
        discount_amount = (delta > 0) ? value : payable;

        String order_id = "w-" + System.currentTimeMillis() + "-" + wardrobe_id + "-" + (value > 0 ? coupon_id : -1);


        Record payment = new Record().set("orderid", order_id).set("pay_amount", pay_amount).set("amount", payable)
                .set("type", "Wardrobe").set("createdAt", new Date())
                .set("updatedAt", new Date()).set("is_paid", 0).set("memberId", Member.getId()).set("coupon", coupon_id)
                .set("wardrobeId", wardrobe_id);
        Db.save("payment", "id", payment);

        int payment_id = Integer.valueOf(payment.get("id").toString());
        return PayParameters.payParameters.Parameters(openid, pay_amount, order_id, payment_id, log, "Wardrobe", discount_amount);
    }

    /**
     * 微信支付
     *
     * @param request
     * @return
     */
    @RequestPath(value = "/pay/submit")
    public Map<String, Object> pay_submit(HttpRequest request) {
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        String openid = (String) body.get("openid");

        JSONArray wardrobe_id = JSON.parseArray(JSON.toJSONString(body.get("wardrobe_id")));
        System.out.println(JSON.toJSONString("wardrobe_id:" + wardrobe_id));
        Integer payment_id = (Integer) body.get("payment_id");
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> query = new HashMap<>();

        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);

        query.put("ids", wardrobe_id);
        List<Wardrobe> Wardrobes = WardrobeService.me.getWardrobes(query);

        query.put("id", payment_id);

        Payment Payment = PaymentService.me.getPayment(query);
        Coupon Coupon;

        if (Payment.getCoupon() != null) {
            query.put("id", Payment.getCoupon());
            Coupon = CouponService.me.getCouponById(Payment.getCoupon());
        } else {
            Coupon = null;
        }


        if (Coupon != null) {
            Coupon.setStatus((short) 3);
            CouponService.me.update(Coupon);
        }

        if (Payment == null) {
            resultMap.put("ok", 1);
            return resultMap;
        }


        for (int i = 0; i < Wardrobes.size(); i++) {
            Wardrobes.get(i).setPaid(true);
            WardrobeService.me.update(Wardrobes.get(i));
        }
        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                Payment.setIsPaid(true);
                PaymentService.me.update(Payment);
                Member.setShow((byte) 1);
                MemberService.me.update(Member);
                return true;
            }
        });
        System.out.println("shiwu");
        resultMap.put("ok", 0);
        return resultMap;

    }

    /**
     * 余额支付
     *
     * @param request
     * @return
     */
    @RequestPath(value = "/chargePay/submit")
    public Map<String, Object> chargePay_submit(HttpRequest request) {
        System.out.println("called");
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        String openid = (String) body.get("openid");
        JSONArray wardrobe_id = JSON.parseArray(JSON.toJSONString(body.get("wardrobe_id")));
        Integer payment_id = (Integer) body.get("payment_id");
        System.out.println("wardrobe:" + wardrobe_id);
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);


        query.put("ids", wardrobe_id);

        List<Wardrobe> Wardrobes = WardrobeService.me.getWardrobes(query);

        query.put("id", payment_id);
        Payment Payment = PaymentService.me.getPayment(query);

        if (Wardrobes == null) {
            resultMap.put("ok", 1);
            resultMap.put("msg", "支付失败");
            return resultMap;
        }

        if (Payment == null) {
            resultMap.put("ok", 1);
            resultMap.put("msg", "支付失败");
            return resultMap;
        }

        if (Member.getBalance() == null || Member.getBalance() < Payment.getPayAmount()) {
            resultMap.put("ok", 1);
            resultMap.put("msg", "支付失败");
            return resultMap;
        }


        Coupon Coupon;

        if (Payment.getCoupon() != null) {
            query.put("id", Payment.getCoupon());
            Coupon = CouponService.me.getCouponById(Payment.getCoupon());
        } else {
            Coupon = null;
        }

        if (Coupon != null) {
            Coupon.setStatus((short) 3);
            CouponService.me.update(Coupon);
        }

        Member.setBalance(Member.getBalance() - Payment.getPayAmount());
        Member.setShow((byte) 1);
        MemberService.me.update(Member);

        Payment.setIsPaid(true);
        PaymentService.me.update(Payment);

        for (int i = 0; i < Wardrobes.size(); i++) {
            Wardrobes.get(i).setPaid(true);
            WardrobeService.me.update(Wardrobes.get(i));
        }

        return resultMap;
    }
}
